/*
 * @Author: Wangtao
 * @Date: 2020-10-26 13:47:18
 * @LastEditors: zhanwang
 * @LastEditTime: 2021-08-26 13:32:20
 */
import { Component, Vue, Prop } from 'vue-property-decorator'
import cloneDeep from 'lodash/cloneDeep'
import { IvrModule } from '@/store/modules/config/ivr'
import { CommonModule } from '@/store/modules/common/index'

import AudioProgress from '@/components/audio/AudioProgress.vue'

const checkReplayTimes = (rule, value, callback) => {
  const boolean = new RegExp('^[0-9][0-9]*$').test(value)
  if (!boolean) {
    callback(new Error('请输入正整数'))
  } else if (value < 0 || value > 3) {
    callback(new Error('重播次数：0-3次'))
  } else {
    callback()
  }
}

const checkreplayInterval = (rule, value, callback) => {
  const boolean = new RegExp('^[0-9][0-9]*$').test(value)
  if (!boolean) {
    callback(new Error('请输入正整数'))
  } else if (value < 1 || value > 10) {
    callback(new Error('重播间隔：1-10秒'))
  } else {
    callback()
  }
}

@Component({
  name: 'exitNodeMixins',
  components: { AudioProgress }
})

export default class extends Vue {
  @Prop({ default: {} }) private data!: any
  @Prop({ default: {} }) public currentNode!: any
  // 校验规则
  private rules = {
    name: [
      { required: true, message: '节点名称必填', trigger: 'change' }
    ],
    playType: [
      { required: true, message: '放音类型必填', trigger: 'change' }
    ],
    voice: [
      { required: true, message: '语音文件必选', trigger: 'change' }
    ],
    replayTimes: [
      { reuired: true, trigger: 'change', validator: checkReplayTimes }
    ],
    replayInterval: [
      { reuired: true, trigger: 'change', validator: checkreplayInterval }
    ],
    default: [
      { required: true, message: '默认流转节点必填', trigger: 'change' }
    ],
    skillsId: [
      { required: true, message: '数据必填', trigger: 'change' }
    ],
    transferVoice: [
      { required: true, message: '语音文件必选', trigger: 'change' }
    ],
    voiceLibrary: [
      { required: true, message: '语音文件必选', trigger: 'change' }
    ],
    guideContent: [
      { required: true, message: '引导文案必填', trigger: 'change' }
    ],
    robotId: [
      { required: true, message: '服务机器人必填', trigger: 'change' }
    ],
    isShowTransfer: [
      { required: true, message: '是否展示转人工必选', trigger: 'change' }
    ]
  }

  public originalConditionLength = 0
  private labelPosition = 'top'
  public robotList: any = [] // 机器人列表
  public formData: any = {}
  // 节点条件
  public condition: any = []
  private lineList: any = []
  private nodeList: any = []
  public currentData: any = {}

  public beforeMount () {
    this.initNodeData()
  }

  private initNodeData () {
    // 当前节点数据
    this.currentData = cloneDeep(this.currentNode)
    // 节点form数据
    this.formData = cloneDeep(this.currentNode.data) || {}
    // 节点连线关系
    this.lineList = cloneDeep(this.data.lineList)
    // 当前ivr所有节点
    this.nodeList = cloneDeep(this.data.nodeList)
    // 原始条件数量
    this.originalConditionLength = this.currentData.condition.length
    this.currentData.condition.forEach((item, index) => {
      const conId = this.currentData.id + '-' + index
      this.condition.push({
        label: item.label,
        value: item.value,
        name: item.name || '',
        to: this.getConditionToId(conId),
        customValue: item.customValue || ''
      })
    })
    this.customMadeValue()
  }

  // 处理定制条件参数的情况
  private customMadeValue () {
    // 初始化默认值
    if (['im-node-date', 'im-node-robot', 'im-node-branch'].includes(this.currentNode.type)) {
      this.formData.default = this.condition[this.condition.length - 1].to
    }
  }

  private getConditionToId (conditionId) {
    let toId = ''
    this.lineList.some((item) => {
      if (item.from === conditionId) {
        toId = item.to
        return true
      }
    })
    return toId
  }

  public onSubmit () {
    (this.$refs as any).nodeForm.validate((valid) => {
      if (valid) {
        for (let i = 0; i < this.condition.length; i++) {
          if (this.currentData.type === 'im-node-branch') {
            if (this.condition[i].to === '') {
              (this as any).$message.error('分支转向必填')
              return false
            }
            if (!this.condition[i].label) {
              this.condition[i].label = `分支${i + 1}`
            }
          }
          this.condition[i].id = this.currentData.id + '-' + i
        }
        this.currentData.condition = this.condition
        if (this.formData.robotId) { // 如果有机器人需要把type 和 name 传给后端
          const robotObj = this.robotList.find(item => {
            return this.formData.robotId === item.robotId
          })
          this.formData.robotName = robotObj.robotName
          this.formData.robotType = robotObj.robotType
        }
        this.currentData.data = this.formData
        this.nodeList.some((item, index) => {
          if (item.id === this.currentData.id) {
            this.nodeList[index] = this.currentData
            return true
          }
        })
        this.$emit('save', this.condition, this.nodeList, this.originalConditionLength)
      } else {
        return false
      }
    })
  }

  private cancel () {
    this.$emit('cancel')
  }

  // 删除某个条件
  private deleteCondition (condition, index) {
    if (this.condition.length > 1) {
      this.condition.splice(index, 1)
    }
  }

  public validateForm () {
    (this.$refs as any).nodeForm.validate()
  }

  public get voiceLibraryList () {
    return CommonModule.publicCache.voiceLibraryList
  }

  public get timeConditionList () {
    return CommonModule.publicCache.timeConditionList
  }

  public get queueList () {
    return CommonModule.publicCache.queueList
  }

  public get userList () {
    return CommonModule.publicCache.userList
  }

  private get currentVoice () {
    let currentVoice = {}
    this.voiceLibraryList.some((item: any) => {
      if (item._id === this.formData.voice || item._id === this.formData.transferVoice) {
        currentVoice = item
      }
    })
    return currentVoice
  }

  private deleteNode () {
    this.$emit('delete', this.currentData)
  }

  private mounted () {
    if (this.currentNode.type === 'im-node-robot') {
      // 获取机器人列表
      const actionData = { url: '/im-robot/action/xbot/list', method: 'POST', data: {} }
      CommonModule.publicAction(actionData).then(res => {
        if (res && res.success) {
          this.robotList = res.list || []
        }
      })
    }
    if (this.currentNode.type === 'im-node-branch') {
      (this as any).$getCache('/im-center/action/webchat/cache', ['platform'], true, true, true, 'POST', true)
    }
  }
}
